package top.xzxsrq.web.utils;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import top.xzxsrq.fileviewutils.entity.SysUserWithRole;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtTokenUtil {

    // Token请求头
    public static final String TOKEN_HEADER = "Authorization";
    // Token前缀
    public static final String TOKEN_PREFIX = "Bearer ";

    // 签名主题
    public static final String SUBJECT = "zhixin";
    // 过期时间
    public static final long EXPIRITION = 1000 * 60 * 60 * 24 * 7;
    // 应用密钥
    public static final String APPSECRET_KEY = "zhixin_jwt_secret";

    /**
     * 生成token
     *
     * @return
     */
    public static String createToken(SysUserWithRole user) {
        Map<String, Object> map = new HashMap<>();
        map.put("sysUser", JSON.toJSONString(user));

        String token = Jwts
                .builder()
                .setClaims(map)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRITION))
                .signWith(SignatureAlgorithm.HS256, APPSECRET_KEY)
                .compact();
        return token;
    }

    /**
     * 校验Token
     */
    public static Claims checkJWT(String token) {
        try {
            return Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            return null;
        }
    }

    public static SysUserWithRole getSysUser(String token) {
        Claims claims = checkJWT(token);
        if (claims != null) {
            String sysUser = claims.get("sysUser", String.class);
            return JSON.parseObject(sysUser, SysUserWithRole.class);
        }
        return null;
    }

    /**
     * 从Token中获取username
     */
    public static String getUsername(String token) {
        SysUserWithRole sysUser = getSysUser(token);
        if (sysUser == null) {
            return null;
        }
        return sysUser.getUsername();
    }

    /**
     * 从Token中获取用户角色
     */
    public static String getUserRole(String token) {
        SysUserWithRole sysUser = getSysUser(token);
        if (sysUser == null) {
            return null;
        }
        return sysUser.getRoleName();
    }

    public static Date getEndTime(String token) {
        try {
            Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody();
            return claims.getExpiration();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 校验Token是否过期
     */
    public static boolean isExpiration(String token) {
        Date endTime = getEndTime(token);
        if (endTime == null) {
            return true;
        }
        return endTime.before(new Date());
    }

}
